/*
 * spring-mvc-logger logs requests/responses
 *
 * Copyright (c) 2013. Israel Zalmanov
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * https://github.com/isrsal/spring-mvc-logger/tree/master/src/main/java/com/github/isrsal/logging
 */

package online.zhangwenzhe.common.trace;

import online.zhangwenzhe.common.identity.SnowFlake;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Description
 *
 * @author zhangwenzhe
 * @since 2018/8/15 下午3:23
 */


//@Component
//@WebFilter(urlPatterns = "/", filterName = "TracingFilter")

public class TracingFilter extends OncePerRequestFilter {


    private static String traceIDHeader = "TraceID";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, final FilterChain filterChain) throws ServletException, IOException {

        long start = System.currentTimeMillis();
        long end = 0;
        //微服务系统中，traceID由网关生成，并存放header中
        long traceId = 0L;

        if (!StringUtils.isEmpty(request.getHeader(traceIDHeader))) {
            traceId = Long.valueOf(request.getHeader(traceIDHeader));
        } else {
            traceId = SnowFlake.next();
        }

        request = new RequestWrapper(traceId, request);
        response = new ResponseWrapper(traceId, response);

        try {
            filterChain.doFilter(request, response);
            end = System.currentTimeMillis();
        } finally {
            TracingLogging.logRequest(request);
            TracingLogging.logResponse((ResponseWrapper) response, end - start);
        }
    }
}
